package com.beau.util;

import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.util.List;

public class IPUtil {

    /**
     * 经过 nginx 转发，获取真实的 ip
     * @param request
     * @return
     */
    public  static String getIpAddr(ServerHttpRequest request)  {
        HttpHeaders headers = request.getHeaders();
        List<String> headList = headers.get("x-forward-for");
        if (headList != null && headList.size() > 0 && "unknown" .equalsIgnoreCase(headList.get(0))) {
            return headList.get(0);
        }
        headList = headers.get("X-Forwarded-For");
        if (headList != null && headList.size() > 0 && "unknown" .equalsIgnoreCase(headList.get(0))) {
            return headList.get(0);
        }
        headList = headers.get("Proxy-Client-IP");
        if (headList != null && headList.size() > 0 && "unknown" .equalsIgnoreCase(headList.get(0))) {
            return headList.get(0);
        }
        headList = headers.get("WL-Proxy-Client-IP");
        if (headList != null && headList.size() > 0 && "unknown" .equalsIgnoreCase(headList.get(0))) {
            return headList.get(0);
        }
        return request.getRemoteAddress().getHostName();
    }

}
